package com.Xingcang_Dianxue.WhutBank.Controllers;

import com.Xingcang_Dianxue.WhutBank.Models.Model;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

public class LoginController implements Initializable {

    @FXML
    public Button login_btn;
    public Button signup_btn;
    public Text text2;

    @FXML
    private PasswordField password_txt;

    @FXML
    private Text text1;

    @FXML
    private Text text3;

    @FXML
    private TextField username_txt;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        username_txt.setOnMouseClicked(mouseEvent -> {
            text3.setText("");
        });
        password_txt.setOnMouseClicked(mouseEvent -> {
            text3.setText("");
        });
        login_btn.setOnAction(actionEvent -> onLogin());
    }


    private void onLogin() {
        Stage stage = (Stage) text1.getScene().getWindow();
            Model.getInstance().evaluateClientCred(username_txt.getText(), password_txt.getText());
            if (Model.getInstance().getClientLoginSuccessFlag()) {
                Model.getInstance().getViewFactory().showClientWindow();
                Model.getInstance().getViewFactory().closeScene(stage);
                stage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, (WindowEvent event) -> {
                    getTimer().cancel();
                });
            } else {
                username_txt.setText("");
                password_txt.setText("");
                text3.setText("No Such Login Credentials.");
                // 给错误信息设置定时器，1秒后消失
                getTimer();
            }
    }

    private Timer getTimer() {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                text3.setText("");
            }
        };
        timer.schedule(task, 1000);

        // 在不需要定时器时取消定时器
        Stage stage = (Stage) text3.getScene().getWindow();
        stage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, (WindowEvent event) -> {
            timer.cancel();
        });

        return timer;
    }


}
